package com.qingcheng.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.netflix.client.http.HttpRequest;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.service.OrderService;
import com.qingcheng.service.WeixinPayService;
import com.qingcheng.util.JwtUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 微信支付
 */
@RestController
@RequestMapping("/wxPay")
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private OrderService orderService;

    @GetMapping("/createNative")
    public Map createNative(String orderId,HttpServletRequest request){
        String username = "Patrick";
        Order order = orderService.queryById(orderId);
        String notifyUrl = "http://chengzhixiong.easy.echosite.cn/orders/wxPay/notify";
        if(order != null){
            if("0".equals(order.getPayStatus()) && "0".equals(order.getOrderStatus()) && username.equals(order.getUsername())){
                return weixinPayService.createNative(order.getId(), order.getPayMoney(), notifyUrl);
            }else{
                return  null;
            }
        }else{
            return null;
        }
    }

    @PostMapping("/notify")
    public void notifyLogic(HttpServletRequest request){
        try {
            InputStream inputStream = (InputStream) request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;

            while ( (len = inputStream.read(buffer))!= -1 ){
                outputStream.write(buffer,0,len);
            }
            inputStream.close();
            outputStream.close();

            String result = new String(outputStream.toByteArray(),"utf-8");
            
            //验证签名信息,成功支付发送消息
            weixinPayService.notifyLogic(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
